/**
 * Hero项目通用工具函数库
 * 
 * 提供项目中常用的工具方法和功能
 * 包含页面跳转、数据处理、UI交互等通用功能
 * 
 * 使用方式：
 * ```html
 * <script src="js/common.js"></script>
 * <script>
 *     // 跳转到管理后台
 *     HeroCommon.gotoAdmin();
 *     
 *     // 跳转到管理后台登录页
 *     HeroCommon.gotoAdmin(true);
 *     
 *     // 格式化日期
 *     const dateStr = HeroCommon.formatDate(new Date());
 *     
 *     // 显示通知
 *     HeroCommon.showNotification('操作成功', 'success');
 * </script>
 * ```
 */

(function() {
    
    // 配置信息
    const CONFIG = {
        // 管理后台地址配置
        ADMIN_BASE_URL: 'http://localhost:80',
        ADMIN_PATH: '/',           // 管理后台首页路径
        ADMIN_LOGIN_PATH: '/',     // 管理后台登录页路径
        
        // 通知配置
        NOTIFICATION_DURATION: 3000,    // 通知显示时长(ms)
        
        // 其他配置
        DATE_FORMAT: 'YYYY-MM-DD HH:mm:ss'
    };
    
    // 工具函数库
    const HeroCommon = {
        
        /**
         * 在新窗口打开管理后台
         * @param {boolean} forceLogin - 是否强制跳转到登录页
         * @param {string} returnUrl - 登录成功后的返回地址
         */
        openAdmin(forceLogin = false, returnUrl = '') {
            try {
                let targetUrl = CONFIG.ADMIN_BASE_URL;
                if (forceLogin) {
                    targetUrl += CONFIG.ADMIN_LOGIN_PATH;
                    if (returnUrl) {
                        targetUrl += '?redirect=' + encodeURIComponent(returnUrl);
                    }
                } else {
                    const isLoggedIn = window.HeroAuth && window.HeroAuth.isLoggedIn();
                    if (isLoggedIn) {
                        targetUrl += CONFIG.ADMIN_PATH;
                    } else {
                        targetUrl += CONFIG.ADMIN_LOGIN_PATH;
                        const redirectUrl = returnUrl || (CONFIG.ADMIN_BASE_URL + CONFIG.ADMIN_PATH);
                        targetUrl += '?redirect=' + encodeURIComponent(redirectUrl);
                    }
                }
                
                console.log(`[HeroCommon] 在新窗口打开管理后台: ${targetUrl}`);
                window.open(targetUrl, '_blank');
                
            } catch (error) {
                console.error('[HeroCommon] 在新窗口打开管理后台失败:', error);
                this.showNotification('打开失败，请稍后重试', 'error');
            }
        },
        
        /**
         * 检查是否在管理后台环境中
         * @returns {boolean} 是否在管理后台
         */
        isInAdmin() {
            return window.location.pathname.startsWith('/index') || 
                   window.location.pathname.startsWith('/login') ||
                   window.location.hash.includes('#/');
        },
        
        /**
         * 格式化日期
         * @param {Date|string|number} date - 日期对象、日期字符串或时间戳
         * @param {string} format - 格式化字符串，默认'YYYY-MM-DD HH:mm:ss'
         * @returns {string} 格式化后的日期字符串
         */
        formatDate(date, format = CONFIG.DATE_FORMAT) {
            try {
                const d = new Date(date);
                if (isNaN(d.getTime())) {
                    return '';
                }
                
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hour = String(d.getHours()).padStart(2, '0');
                const minute = String(d.getMinutes()).padStart(2, '0');
                const second = String(d.getSeconds()).padStart(2, '0');
                
                return format
                    .replace('YYYY', year)
                    .replace('MM', month)
                    .replace('DD', day)
                    .replace('HH', hour)
                    .replace('mm', minute)
                    .replace('ss', second);
            } catch (error) {
                console.error('[HeroCommon] 日期格式化失败:', error);
                return '';
            }
        },
        
        /**
         * 显示通知消息
         * @param {string} message - 消息内容
         * @param {string} type - 消息类型: success, error, warning, info
         * @param {number} duration - 显示时长，默认3秒
         */
        showNotification(message, type = 'info', duration = CONFIG.NOTIFICATION_DURATION) {
            try {
                // 创建通知元素
                const notification = document.createElement('div');
                notification.className = `hero-notification hero-notification-${type}`;
                notification.innerHTML = `
                    <div class="hero-notification-content">
                        <span class="hero-notification-icon">${this.getNotificationIcon(type)}</span>
                        <span class="hero-notification-text">${message}</span>
                        <button class="hero-notification-close" onclick="this.parentElement.parentElement.remove()">&times;</button>
                    </div>
                `;
                
                // 添加样式
                this.ensureNotificationStyles();
                
                // 添加到页面
                document.body.appendChild(notification);
                
                // 显示动画
                setTimeout(() => {
                    notification.classList.add('hero-notification-show');
                }, 100);
                
                // 自动移除
                setTimeout(() => {
                    notification.classList.remove('hero-notification-show');
                    setTimeout(() => {
                        if (notification.parentElement) {
                            notification.parentElement.removeChild(notification);
                        }
                    }, 300);
                }, duration);
                
            } catch (error) {
                console.error('[HeroCommon] 显示通知失败:', error);
                // 降级到alert
                alert(message);
            }
        },
        
        /**
         * 获取通知图标
         * @param {string} type - 通知类型
         * @returns {string} 图标HTML
         */
        getNotificationIcon(type) {
            const icons = {
                success: '✓',
                error: '✕',
                warning: '⚠',
                info: 'ⓘ'
            };
            return icons[type] || icons.info;
        },
        
        /**
         * 确保通知样式存在
         */
        ensureNotificationStyles() {
            if (!document.getElementById('hero-notification-styles')) {
                const styles = document.createElement('style');
                styles.id = 'hero-notification-styles';
                styles.innerHTML = `
                    .hero-notification {
                        position: fixed;
                        top: 20px;
                        right: 20px;
                        min-width: 300px;
                        max-width: 500px;
                        z-index: 10001;
                        transform: translateX(100%);
                        opacity: 0;
                        transition: all 0.3s ease;
                    }
                    
                    .hero-notification-show {
                        transform: translateX(0);
                        opacity: 1;
                    }
                    
                    .hero-notification-content {
                        display: flex;
                        align-items: center;
                        padding: 12px 16px;
                        border-radius: 8px;
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                        background: white;
                        border-left: 4px solid #667eea;
                    }
                    
                    .hero-notification-success .hero-notification-content {
                        border-left-color: #10b981;
                        background: #f0fdf4;
                    }
                    
                    .hero-notification-error .hero-notification-content {
                        border-left-color: #ef4444;
                        background: #fef2f2;
                    }
                    
                    .hero-notification-warning .hero-notification-content {
                        border-left-color: #f59e0b;
                        background: #fffbeb;
                    }
                    
                    .hero-notification-info .hero-notification-content {
                        border-left-color: #3b82f6;
                        background: #eff6ff;
                    }
                    
                    .hero-notification-icon {
                        font-size: 16px;
                        margin-right: 8px;
                        font-weight: bold;
                    }
                    
                    .hero-notification-success .hero-notification-icon {
                        color: #10b981;
                    }
                    
                    .hero-notification-error .hero-notification-icon {
                        color: #ef4444;
                    }
                    
                    .hero-notification-warning .hero-notification-icon {
                        color: #f59e0b;
                    }
                    
                    .hero-notification-info .hero-notification-icon {
                        color: #3b82f6;
                    }
                    
                    .hero-notification-text {
                        flex: 1;
                        color: #374151;
                        font-size: 14px;
                        line-height: 1.4;
                    }
                    
                    .hero-notification-close {
                        background: none;
                        border: none;
                        font-size: 18px;
                        cursor: pointer;
                        color: #6b7280;
                        margin-left: 8px;
                        padding: 0;
                        line-height: 1;
                    }
                    
                    .hero-notification-close:hover {
                        color: #374151;
                    }
                    
                    @media (max-width: 768px) {
                        .hero-notification {
                            right: 10px;
                            left: 10px;
                            min-width: auto;
                            max-width: none;
                        }
                    }
                `;
                document.head.appendChild(styles);
            }
        },
        
        /**
         * 防抖函数
         * @param {Function} func - 要防抖的函数
         * @param {number} wait - 等待时间(ms)
         * @returns {Function} 防抖后的函数
         */
        debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        },
        
        /**
         * 节流函数
         * @param {Function} func - 要节流的函数
         * @param {number} limit - 时间间隔(ms)
         * @returns {Function} 节流后的函数
         */
        throttle(func, limit) {
            let inThrottle;
            return function() {
                const args = arguments;
                const context = this;
                if (!inThrottle) {
                    func.apply(context, args);
                    inThrottle = true;
                    setTimeout(() => inThrottle = false, limit);
                }
            };
        },
        
        /**
         * 深拷贝对象
         * @param {any} obj - 要拷贝的对象
         * @returns {any} 拷贝后的对象
         */
        deepClone(obj) {
            if (obj === null || typeof obj !== 'object') {
                return obj;
            }
            if (obj instanceof Date) {
                return new Date(obj.getTime());
            }
            if (obj instanceof Array) {
                return obj.map(item => this.deepClone(item));
            }
            if (typeof obj === 'object') {
                const cloned = {};
                Object.keys(obj).forEach(key => {
                    cloned[key] = this.deepClone(obj[key]);
                });
                return cloned;
            }
        },
        
        /**
         * 获取URL参数
         * @param {string} name - 参数名
         * @returns {string|null} 参数值
         */
        getUrlParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        },
        
        /**
         * 设置页面标题
         * @param {string} title - 页面标题
         */
        setTitle(title) {
            document.title = title;
        },
        
        /**
         * 滚动到顶部
         * @param {number} duration - 动画时长(ms)
         */
        scrollToTop(duration = 500) {
            const start = window.pageYOffset;
            const startTime = performance.now();
            
            const animateScroll = (currentTime) => {
                const timeElapsed = currentTime - startTime;
                const progress = Math.min(timeElapsed / duration, 1);
                const ease = progress * (2 - progress); // easeOutQuad
                
                window.scrollTo(0, start * (1 - ease));
                
                if (timeElapsed < duration) {
                    requestAnimationFrame(animateScroll);
                }
            };
            
            requestAnimationFrame(animateScroll);
        },
        
        /**
         * 获取配置信息
         * @param {string} key - 配置键
         * @returns {any} 配置值
         */
        getConfig(key) {
            return CONFIG[key];
        },
        
        /**
         * 设置配置信息
         * @param {string} key - 配置键
         * @param {any} value - 配置值
         */
        setConfig(key, value) {
            CONFIG[key] = value;
        }
    };
    
    // 全局暴露
    window.HeroCommon = HeroCommon;
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('[HeroCommon] 通用工具库已加载');
        
        // 触发初始化事件
        document.dispatchEvent(new CustomEvent('hero:commonReady'));
    });
    
})();